<?php
namespace RMD\AccountBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

use RMD\AccountBundle\Entity\GroupSet;
use RMD\AccountBundle\Form\DataTransformer\TestTransformer;

class SubscriberGroupType extends AbstractType
{
	private $unmappedFields = array();
	public function buildForm(FormBuilderInterface $builder, array $options) {
		
        $builder->add('firstname', 'text', array('required' => false));
        $builder->add('lastname', 'text', array('required' => false));
        $builder->add('email', 'email');
        $builder->add('description', 'textarea', array('required' => false));
		$groups = array();
		foreach ($options['data']->getGroups() as $group) {
			$groups[] = $group->getId();
		}
		foreach ($options['data']->getList()->getGroupSets() as $groupSet) {
			//var_dump($groupSet);
			$title = 'groupSet_' . $groupSet->getId();
			$this->unmappedFields[] = $title;
			$choices = array();
			$multiple = false;
			$data = '';
			if ($groupSet->getSelectType() == GroupSet::MULTI_CHOICE) {
				$multiple = true;
				$data = array();
			}
			
			foreach ($groupSet->getGroups() as $group) {
				$groupId = $group->getId();
				$choices[$groupId] = $group->getTitle();
				if (in_array($groupId, $groups)) {
					if ($multiple) {
						$data[] = $groupId;
					} else {
						$data = $groupId;
					}
					
				}
			}
			//var_dump();
			$builder->add($title, 'choice', array(
				'choices'   => $choices,
				'multiple' => $multiple,
				'mapped' => false,
				'required' => false,
				'expanded' => true,
				'label' => $groupSet->getTitle(),
				'data' => $data
				)
			);
			//$builder->add($title, new GroupTestType(), array('mapped' => false, 'data' => $groupSet));

		}
		/*$builder->add('groupz', 'collection', array(
				'type' => new GroupTestType($groupSet),
				'by_reference' => false
			));*/
		/*$multiple = false;
		if ($options['data']->getSelectType() == GroupSet::MULTI_CHOICE) {
			$multiple = true;
		}*/
		
		//$transformer = new TestTransformer();
		/*$builder->add($builder->create('groupz', 'choice', array(
			'choices'   => $choices,
			'multiple'  => $multiple,
			'expanded' => true,
			'required'    => false
			))//->prependNormTransformer($transformer)
		);*/
	}

    public function getName() {
        return 'subscribergroup';
    }
    
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'RMD\AccountBundle\Entity\Subscriber',
            'intention'       => 'subscribergroup_item'
        ));
		$resolver->setRequired(array('em'));
    }
	public function getUnmappedFields(){
		return $this->unmappedFields;
	}
}
?>
